﻿# ------------------------------------------------------ #
# Active Directory Domain Services (ADDS) Configuration #
# ------------------------------------------------------ #
param([string]$virtualMachineService, [string]$virtualMachineName)

Write-Information "Virtual machine '$virtualMachineName' executing Active Directory '$($script.type)' configuration ... " -NoNewLine $true
$session = Get-VirtualMachineInstancePowerShellSession -Subscription $subscription -VirtualMachineName $virtualMachineName -ForceDomainLogin $script.domainLogin
switch ($script.type)
{
	"Primary"
	{
		# Install new forest root domain
        $restart = Invoke-Command -Session $session -ScriptBlock {
	        param([string]$userName, [string]$password, [string]$dnsDomain, [string]$netBiosDomainName)
	        Set-ExecutionPolicy Unrestricted -Force
	        $folderNTDS = "F:\DATA"
	        $folderNTDSLogs = "F:\LOGS"
	        $folderSYSVOL = "F:\SYSVOL"
            if (!(Test-Path -LiteralPath $folderNTDS)) { $operation = [IO.Directory]::CreateDirectory($folderNTDS) }
	        if (!(Test-Path -LiteralPath $folderNTDSLogs)) { $operation = [IO.Directory]::CreateDirectory($folderNTDSLogs) }
	        if (!(Test-Path -LiteralPath $folderSYSVOL)) { $operation = [IO.Directory]::CreateDirectory($folderSYSVOL) }
		    $operation = Install-WindowsFeature -Name AD-Domain-Services –IncludeManagementTools -Restart:$false -WarningAction Ignore
            try { $dc = Get-ADDomainController } catch { }
            if ($dc -ne $null -and $dc.Name -eq $Env:COMPUTERNAME) { return $false }
		    $securePassword = ConvertTo-SecureString $password -AsPlainText -Force
            $operation = Install-ADDSForest -DomainName $dnsDomain -DomainNetbiosName $netBiosDomainName -ForestMode Win2012 -DomainMode Win2012 -SafeModeAdministratorPassword $securePassword `
                -DatabasePath $folderNTDS -LogPath $folderNTDSLogs -SysvolPath $folderSYSVOL -InstallDns:$true -CreateDnsDelegation:$false -NoRebootOnCompletion:$false -Force:$true -WarningAction Ignore
            return $true
        } -ArgumentList $subscription.virtualMachines.adminUserName, $subscription.virtualMachines.password, $subscription.virtualMachines.dnsDomain, $subscription.virtualMachines.netBiosDomain
	}
	"Replica"
	{
        # Install replica domain
        $restart = Invoke-Command -Session $session -ScriptBlock {
	        param([string]$userName, [string]$password, [string]$dnsDomain, [string]$netBiosDomainName, [string]$siteName, [string]$replicationSource)
	        Set-ExecutionPolicy Unrestricted -Force
	        $folderNTDS = "F:\DATA"
	        $folderNTDSLogs = "F:\LOGS"
	        $folderSYSVOL = "F:\SYSVOL"
            if (!(Test-Path -LiteralPath $folderNTDS)) { $operation = [IO.Directory]::CreateDirectory($folderNTDS) }
	        if (!(Test-Path -LiteralPath $folderNTDSLogs)) { $operation = [IO.Directory]::CreateDirectory($folderNTDSLogs) }
	        if (!(Test-Path -LiteralPath $folderSYSVOL)) { $operation = [IO.Directory]::CreateDirectory($folderSYSVOL) }
		    $operation = Install-WindowsFeature -Name AD-Domain-Services –IncludeManagementTools -Restart:$false -WarningAction Ignore
            try { $dc = Get-ADDomainController } catch { }
            if ($dc -ne $null -and $dc.Name -eq $Env:COMPUTERNAME) { return $false }
		    $securePassword = ConvertTo-SecureString $password -AsPlainText -Force
		    $credential = New-Object System.Management.Automation.PSCredential("$netBiosDomainName\$userName", $securePassword)
            $operation = Install-ADDSDomainController -Credential $credential -SafeModeAdministratorPassword $securePassword `
                -DomainName $dnsDomain -SiteName $siteName -ReplicationSourceDC $replicationSource `
                -DatabasePath $folderNTDS -LogPath $folderNTDSLogs -SysvolPath $folderSYSVOL `
                -AllowDomainControllerReinstall -InstallDns:$true -Force:$true -NoGlobalCatalog:$false -CreateDnsDelegation:$false -CriticalReplicationOnly:$false -NoRebootOnCompletion:$true -WarningAction Ignore
            return $true
        } -ArgumentList $subscription.virtualMachines.adminUserName, $subscription.virtualMachines.password, $subscription.virtualMachines.dnsDomain, $subscription.virtualMachines.netBiosDomain, $script.siteName, $script.replicationSource
	}
	"Initialize"
	{
		# Initialize Active Directory module for Windows PowerShell
        $restart = $false
        do
        {
            $initialized = $true
            try
            {
                Invoke-Command -Session $session -ScriptBlock {
                    Import-Module ActiveDirectory
                    Get-ADDomain | Out-Null
                }
            }
            catch
            {
                if ($_.Exception.Message -like "*Attempting to perform the InitializeDefaultDrives operation on the 'ActiveDirectory' provider failed.*" -or `
                    $_.Exception.Message -like "*Unable to find a default server with Active Directory Web Services running.*")
                {
                    $initialized = $false
                    Remove-PSSession $session
                    Start-Sleep 3
                    $session = Get-VirtualMachineInstancePowerShellSession -Subscription $subscription -VirtualMachineName $virtualMachineName -ForceDomainLogin $script.domainLogin
                }
                else
                {
                    throw $_.Exception.Message
                }
            }
        } until ($initialized)
	}
	default
	{
		throw "Active Directory type '$($script.type)' is not supported."
	}
}
# Troubleshooting
# - Check 'C:\Windows\debug\dcpromo.log' for failures
# - dcdiag /test:dns
Remove-PSSession $session
Write-Text "done."
if ($restart)
{
    Restart-VirtualMachineInstance $subscription $virtualMachineService $virtualMachineName $false "WinRM"
}